﻿using UnityEngine;
using System.Collections;

public class GameScript : MonoBehaviour {

    public float spawnTime, spawnDelay;
    public GameObject[] target;
    public int minRandom, maxRandom;
    public GUIText completeText, failedText, timerText, chanceText, scoreText;
    int finishTime, restTime;
    bool isCompleted, isGameOver;

	// Use this for initialization
	void Start () 
    {
        isCompleted = false;
        isGameOver = false;
        InitGUI();
        InvokeRepeating("SpawnEnemy", spawnDelay, spawnTime);

        GameEventManager.GameOver += GameOver;
	}

	// Update is called once per frame
	void Update () 
    {
        if (!isGameOver)
        {
            restTime = finishTime - (int)Time.time;
            if (restTime >= 0)
            {
                timerText.text = restTime.ToString();
            }
            else
            {
                timerText.text = "0";
                GameEventManager.TriggerGameOver();
            }

            chanceText.text = "Chance: " + PlayerScript.lives.ToString();
            if (PlayerScript.lives == 0)
            {
                GameEventManager.TriggerGameOver();
            }

            scoreText.text = PlayerScript.points.ToString() + "/10";
            if (PlayerScript.points == 10)
            {
                isCompleted = true;
                GameEventManager.TriggerGameOver();
            }
        }
	}

    void InitGUI()
    {
        completeText.transform.position = new Vector2(transform.position.x + 9.6f, transform.position.y - 3.5f);
        failedText.transform.position = new Vector2(transform.position.x + 9.6f, transform.position.y - 3.5f);
        timerText.transform.position = new Vector2(transform.position.x + 9.6f, transform.position.y - 3f);
        chanceText.transform.position = new Vector2(transform.position.x + 9.1f, transform.position.y - 3f);
        scoreText.transform.position = new Vector2(transform.position.x + 10.02f, transform.position.y - 3f);

        completeText.enabled = false;
        failedText.enabled = false;

        finishTime = (int)Time.time + 30;
    }

    void SpawnEnemy()
    {
        int rand = Random.Range(minRandom, maxRandom);
        if (rand != maxRandom - 1)
            Instantiate(target[0], transform.position, transform.rotation);
        else Instantiate(target[1], transform.position, transform.rotation);
    }

    void GameOver()
    {
        isGameOver = true;
        if (isCompleted)
            completeText.enabled = true;
        else failedText.enabled = true;

        //enabled = false;
    }

    void OnGUI()
    {
        if (isGameOver)
        {
            if (GUI.Button(new Rect(Screen.width / 2 - 20, Screen.height / 2 + 20, 40, 30), "OK"))
            {
                Application.LoadLevel(0);
            }
        }
    }
}
